<?php

namespace App\Http\Resources\Base;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Pagination\LengthAwarePaginator;

class BaseResourceCollection extends ResourceCollection
{
    /**
     * Create an HTTP response that represents the object.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return JsonResponse
     */
    public function toResponse($request)
    {
        $response = $this->resource instanceof LengthAwarePaginator
            ? (new CustomPaginatedResourceResponse($this))->toResponse($request)
            : parent::toResponse($request);

        $encodingOptions = JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES;

        if (config('app.debug')) {
            // 调试的时候可能会用到
            $encodingOptions += JSON_PRETTY_PRINT;
        }
        $response->setData($this->withWrapData($response));
        // 包裹条件
        // 处理中文转码
        return $response->setEncodingOptions($encodingOptions);
    }

    public function withWrapData($response)
    {
        /** @var JsonResponse $response */
        $data = $response->getData(true);

        $paginate = $data['meta'] ?? [];
        $result['list'] = $data['data'] ?? [];
        if ($paginate) {
            $result['meta'] = $data['meta'] ?? [
                'page' => 1,
                'limit' => 10,
                'has_more' => false,
                'total' => 0,];
        }
        array_forget($data, ['data', 'meta']);
        // 支持扩展参数
        return array_merge($result, $data);
    }
}
